package com.xwdeshj.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xwdeshj.dal.Dal_XwBusinessinfo;
import com.xwdeshj.entity.*;
import com.xwdeshj.repository.*;
import com.xwdeshj.service.MailServcie;
import com.xwdeshj.service.XwBusinessInfoService;
import com.xwdeshj.utils.DateUtil;
import com.xwdeshj.utils.StringUtil;
import com.xwdeshj.utils.helper;
import lombok.extern.slf4j.Slf4j;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by BKWJA on 2018/12/22.
 * 商家信息/主管审核表实现层
 */
@Slf4j
@Service("xwBusinessInfoService")
public class XwBusinessInfoServiceImpl implements XwBusinessInfoService {

    @Autowired
    private XwBusinessInfoRepository xwBusinessInfoRepository;
    @Autowired
    private XwUserinfoRepository xwUserinfoRepository;
    @Autowired
    private XwFarmBasicinfoRepository xwFarmBasicinfoRepository;
    @Autowired
    private XwScenicBasicinfoRepository xwScenicBasicinfoRepository;
    @Autowired
    private XwFarmRoominfoRepository xwFarmRoominfoRepository;
    @Autowired
    private XwFarmCollectinfoRepository xwFarmCollectinfoRepository;
    @Autowired
    private XwFarmAtlasinfoRepository xwFarmAtlasinfoRepository;
    @Autowired
    private XwFarmFoodinfoRepository xwFarmFoodinfoRepository;
    @Autowired
    private XwFarmDiscussinfoRepository xwFarmDiscussinfoRepository;

    @Autowired
    private XwSceincCollectinfoReository xwSceincCollectinfoReository;
    @Autowired
    private XwSceincDiscussinfoReopsitory xwSceincDiscussinfoReopsitory;
    @Autowired
    private XwSceincEntertainmentRepository xwSceincEntertainmentRepository;
    @Autowired
    private XwScenicAtlasinfoRepository xwScenicAtlasinfoRepository;
    @Autowired
    private XwCustomShopRepository xwCustomShopRepository;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private Sid sid;

    //邮件服务
    @Autowired
    private MailServcie mailServcie;
    @Resource
    private TemplateEngine templateEngine;

    Dal_XwBusinessinfo dal_xwBusinessinfo = new Dal_XwBusinessinfo();

    public Dal_XwBusinessinfo getDal_xwBusinessinfo() {
        return dal_xwBusinessinfo;
    }

    public void setDal_xwBusinessinfo(Dal_XwBusinessinfo dal_xwBusinessinfo) {
        this.dal_xwBusinessinfo = dal_xwBusinessinfo;
    }

    /**
     * 升级为商家（农家乐）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public JSONObject upgradeBusines(String tab, String user_encryptId, String business_Legal,
                                     String business_Credit, String business_license, String business_tel,
                                     String business_create, String business_type, String farm_tour_type,
                                     String Business_area, String dining_reception, String room, String scale,
                                     String consume, String city, String district, String address,
                                     String intr_info, String bus_route, String Self_route,
                                     String Remarks, String CompanyName, Integer tradestatus, String applicant_checkencryptId,
                                     String Type_encryptId) {

        JSONObject result = new JSONObject();
        if (!"".equals(user_encryptId) && user_encryptId != null) {

            XwUserinfo user = new XwUserinfo();
            user.setUserEncryptid(user_encryptId);
            boolean flag = xwUserinfoRepository.exists(Example.of(user));
            if (flag) {
                if ("1".equals(tab)) {

                    //更改用户信息
                    XwUserinfo userinfo = xwUserinfoRepository.findByUserEncryptid(user_encryptId);
                    if ("0".equals(userinfo.getUserRole())) {
                        userinfo.setUserRole("1");
                        String userTel = userinfo.getUserTel();
                        if( !userTel.equals(business_tel)){
                            /**
                             *  更改联系方式后
                             *  1、验证电话号码是否已经存在
                             *  2、存在，则判断该电话号码是否是 用户之前的电话号码，若是 则不管，
                             *  不是：则更改为最新的电话号码
                             */
                            List<XwUserinfo> listUserTel = xwUserinfoRepository.findByUserTel(business_tel.trim());
                            if (listUserTel.size() == 0){
                                userinfo.setUserTel(business_tel);
                            }else {
                                result.put("status", 0);
                                result.put("msg", "联系电话已被他人注册！");
                                return  result;
                            }
                        }
                        userinfo.setUserUpdatetime(new Date());
                        xwUserinfoRepository.save(userinfo);


                        //封装农家乐商家，存储商家基本信息
                        String farm_encryptId = sid.nextShort();
                        XwBusinessInfo businessInfo = getRequestXwBusinessInfoData(user_encryptId,userinfo.getUserName(),business_tel,
                                business_Legal,business_license,CompanyName,business_create,
                                business_Credit,business_type,Remarks,applicant_checkencryptId,
                                farm_encryptId,"0");

                        try {
                            //保存商家基本信息
                            xwBusinessInfoRepository.save(businessInfo);

                            //封装农家乐店铺基本信息
                            XwFarmBasicinfo farmBasicinfo = getRequestXwFarmBasicinfoData(user_encryptId,business_type,
                                    farm_tour_type,Type_encryptId,Business_area,dining_reception,room,scale,consume,
                                    city,district,address,tradestatus,intr_info,bus_route,Self_route,farm_encryptId);

                            try {
                                //保存农家乐店铺基本信息
                                xwFarmBasicinfoRepository.save(farmBasicinfo);
                                result.put("status", 0);
                                result.put("msg", "ok");
                            } catch (Exception e) {
                                e.printStackTrace();
                                result.put("status", 500);
                                result.put("msg", "保存农家乐店铺基本信息出现错误！");
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            result.put("status", 500);
                            result.put("msg", "保存商家基本信息出现错误！");
                        }

                    } else {
                        result.put("status", 500);
                        result.put("msg", "升级为商家失败，类型不一致，请联系管理员！");
                    }
                } else {
                    result.put("status", 500);
                    result.put("msg", "该用户已经是商家，无法再次进行升级！");
                }

            } else {
                result.put("status", 500);
                result.put("msg", "该用户不存在，无法升级为商家，请先注册！");
            }

        } else {
            result.put("status", 500);
            result.put("msg", "user_encryptId不能为空！");
        }
        System.out.println("upgradeBusines:" + result.toString());
        return result;
    }

    /**
     * 升级为商家（景区）
     */
    @Override
    @Modifying
    @Transactional(rollbackFor = Exception.class)
    public JSONObject upgradeSecBusines(String tab, String user_encryptId, String business_Legal,
                                        String business_Credit, String business_license, String business_tel,
                                        String business_create, String business_type, String farm_tour_type,
                                        double scenic_Ticket, String tour_kftime, String scenic_suit,
                                        String sceni_suit_encryptId, String scenic_season, String city,
                                        String district, String address, String intr_info, String bus_route,
                                        String Self_route, String Remarks, String CompanyName, String scenic_grade,
                                        String Type_encryptId, HttpServletRequest request) {


        JSONObject result = new JSONObject();
        if (!"".equals(user_encryptId) && user_encryptId != null) {

            XwUserinfo user = new XwUserinfo();
            user.setUserEncryptid(user_encryptId);
            boolean flag = xwUserinfoRepository.exists(Example.of(user));
            if (flag) {
                if ("2".equals(tab)) {

                    //更改用户信息
                    XwUserinfo userinfo = xwUserinfoRepository.findByUserEncryptid(user_encryptId);
                    if ("0".equals(userinfo.getUserRole())) {
                        userinfo.setUserRole("1");
                        String userTel = userinfo.getUserTel();
                        if( !userTel.equals(business_tel)){
                            /**
                             *  更改联系方式后
                             *  1、验证电话号码是否已经存在
                             *  2、存在，则判断该电话号码是否是 用户之前的电话号码，若是 则不管，
                             *  不是：则更改为最新的电话号码
                             */
                            List<XwUserinfo> listUserTel = xwUserinfoRepository.findByUserTel(business_tel.trim());
                            if (listUserTel.size() == 0){
                                userinfo.setUserTel(business_tel);
                            }else {
                                result.put("status", 0);
                                result.put("msg", "联系电话已被他人注册！");
                                return  result;
                            }
                        }
                        userinfo.setUserUpdatetime(new Date());
                        xwUserinfoRepository.save(userinfo);

                        //申请人加密id  申请人加密id
                        String applicant_checkencryptId = helper.ReadCookieMap(request, "uid_encryptid").toString();

                        //升级为农家乐商家，封装 存储商家基本信息
                        String sce_encryptId = sid.nextShort();
                        XwBusinessInfo businessInfo = getRequestXwBusinessInfoData(user_encryptId,userinfo.getUserName(),business_tel,
                                business_Legal,business_license,CompanyName,business_create,
                                business_Credit,business_type,Remarks,applicant_checkencryptId,
                                "0",sce_encryptId);

                        try {
                            //保存商家基本信息
                            xwBusinessInfoRepository.save(businessInfo);

                            //景区店铺基本信息
                            XwScenicBasicinfo scenicBasicinfo = getRequestXwScenicBasicinfoData(user_encryptId,business_type,
                                    farm_tour_type,Type_encryptId,scenic_Ticket,tour_kftime,
                                    scenic_suit,sceni_suit_encryptId,scenic_season,scenic_grade,
                                    city,district, address,intr_info,bus_route,Self_route,
                                    sce_encryptId);
//
                            try {
                                //保存景区店铺基本信息
                                xwScenicBasicinfoRepository.save(scenicBasicinfo);
                                result.put("status", 0);
                                result.put("msg", "ok");
                            } catch (Exception e) {
                                e.printStackTrace();
                                result.put("status", 500);
                                result.put("msg", e);
                                result.put("errmsg", "保存农家乐店铺基本信息出现错误！");
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            result.put("status", 500);
                            result.put("msg", e);
                            result.put("errmsg", "保存商家基本信息出现错误！");
                        }

                    } else {
                        result.put("status", 500);
                        result.put("msg", "升级为商家失败，类型不一致，请联系管理员！");
                    }
                } else {
                    result.put("status", 500);
                    result.put("msg", "该用户已经是商家，无法再次进行升级！");
                }

            } else {
                result.put("status", 500);
                result.put("msg", "该用户不存在，无法升级为商家，请先注册！");
            }

        } else {
            result.put("status", 500);
            result.put("msg", "user_encryptId不能为空！");
        }
        System.out.println("upgradeSecBusines:" + result.toString());
        return result;
    }


    @Override
    public JSONObject getbusinessinfolist(Integer pageindex, Integer pagesize, String starttime, String endtime,
                                          String sortfild, String sortway, String business_type, String reviewStatus,
                                          String searchval, String searchkey,HttpServletRequest request) {

        JSONObject result = new JSONObject();

        result = dal_xwBusinessinfo.getbusinessinfolist(pageindex,pagesize,starttime,endtime,sortfild,sortway,
                business_type,reviewStatus,searchval,searchkey,jdbcTemplate);


        System.out.println("getbusinessinfolist:" + result.toString());
        return result;
    }

    /**
     * 删除商家基本信息,用于解决jpa方法的先后顺序
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public JSONObject delbusinessinfo(String business_encryptId, String farm_encryptId, String sec_encryptId,
                                      HttpServletRequest request) {
        JSONObject result = new JSONObject();
        String uid = helper.ReadCookieMap(request,"uid").toString();//读取当前操作人用户id
        String u_encryptid = helper.ReadCookieMap(request,"uid_encryptid").toString();//读取当前操作人用户加密id
        if((!"".equals(uid) && uid != null) && (!"".equals(u_encryptid) && u_encryptid != null)){
            if (!"".equals(business_encryptId) && business_encryptId != null) {
                try {
                    if (business_encryptId.indexOf(",") == -1) {

                        XwBusinessInfo businessInfo = new XwBusinessInfo();
                        businessInfo.setBusinessEncryptid(business_encryptId);
                        boolean temp = xwBusinessInfoRepository.exists(Example.of(businessInfo));

                        if (temp) {
                            //存在
                            if (!"0".equals(farm_encryptId) && !"".equals(farm_encryptId)) {
                                //删除农家乐商家信息，单个删除

                                //农家乐图集
                                XwFarmAtlasinfo xwFarmAtlasinfo = new XwFarmAtlasinfo();
                                xwFarmAtlasinfo.setFarmEncryptid(farm_encryptId);
                                xwFarmAtlasinfo.setBusinessEncryptid(business_encryptId);
                                boolean atlastemp = xwFarmAtlasinfoRepository.exists(Example.of(xwFarmAtlasinfo));
                                if(atlastemp){
                                    //查询到有相关记录
                                    xwFarmAtlasinfoRepository.deleteByFarmEncryptid(farm_encryptId);
                                }

                                //农家乐收藏信息
                                XwFarmCollectinfo xwFarmCollectinfo = new XwFarmCollectinfo();
                                xwFarmCollectinfo.setBusinessEncryptid(business_encryptId);
                                xwFarmCollectinfo.setFarmtypeEncryptid(farm_encryptId);
                                boolean colltemp = xwFarmCollectinfoRepository.exists(Example.of(xwFarmCollectinfo));
                                if (colltemp){
                                    //查询到有相关记录
                                    xwFarmCollectinfoRepository.deleteByFarmEncryptid(farm_encryptId);
                                }

                                //农家乐评论信息
                                XwFarmDiscussinfo xwFarmDiscussinfo = new XwFarmDiscussinfo();
                                xwFarmDiscussinfo.setBusinessEncryptid(business_encryptId);
                                xwFarmDiscussinfo.setFarmEncryptid(farm_encryptId);
                                boolean disctemp = xwFarmDiscussinfoRepository.exists(Example.of(xwFarmDiscussinfo));
                                if(disctemp){
                                    //查询到有相关记录
                                    xwFarmDiscussinfoRepository.deleteByFarmEncryptid(farm_encryptId);
                                }

                                //农家乐美食信息
                                XwFarmFoodinfo xwFarmFoodinfo = new XwFarmFoodinfo();
                                xwFarmFoodinfo.setBusinessEncryptid(business_encryptId);
                                xwFarmFoodinfo.setFarmEncryptid(farm_encryptId);
                                boolean foodtemp = xwFarmFoodinfoRepository.exists(Example.of(xwFarmFoodinfo));
                                if(foodtemp){
                                    //查询到有相关记录
                                    xwFarmFoodinfoRepository.deleteByFarmEncryptid(farm_encryptId);
                                }

                                //农家乐住宿信息
                                XwFarmRoominfo xwFarmRoominfo = new XwFarmRoominfo();
                                xwFarmRoominfo.setBusinessEncryptid(business_encryptId);
                                xwFarmRoominfo.setFarmEncryptid(farm_encryptId);
                                boolean roomtemp = xwFarmRoominfoRepository.exists(Example.of(xwFarmRoominfo));
                                if(roomtemp){
                                    //查询到有相关记录
                                    xwFarmRoominfoRepository.deleteByFarmEncryptid(farm_encryptId);
                                }

                                //农家店铺基本信息
                                XwFarmBasicinfo xwFarmBasicinfo = new XwFarmBasicinfo();
                                xwFarmBasicinfo.setBusinessEncryptid(business_encryptId);
                                xwFarmBasicinfo.setFarmEncryptid(farm_encryptId);
                                boolean farmbastmep = xwFarmBasicinfoRepository.exists(Example.of(xwFarmBasicinfo));
                                if(farmbastmep){
                                    //查询到有相关记录
                                    xwFarmBasicinfoRepository.deleteByFarmEncryptid(farm_encryptId);
                                }

                                //删除匹配对应商户类型的记录
                                XwCustomShop xwCustomShop = new XwCustomShop();
                                xwCustomShop.setShopEncryptid(farm_encryptId);
                                boolean shoptemp = xwCustomShopRepository.exists(Example.of(xwCustomShop));
                                if(shoptemp){
                                    xwCustomShopRepository.deleteByShopEncryptid(farm_encryptId);
                                }

                                //用户基本信息
                                XwUserinfo userinfo = xwUserinfoRepository.findByUserEncryptid(business_encryptId);
                                if(userinfo != null){
                                    userinfo.setUserRole("0");
                                    xwUserinfoRepository.save(userinfo);
                                }
                                xwBusinessInfoRepository.deleteByBusinessEncryptid(business_encryptId);

                            } else if (!"0".equals(sec_encryptId) && !"".equals(sec_encryptId)) {
                                //删除景区的商家信息

                                //景区收藏信息
                                XwSceincCollectinfo xwSceincCollectinfo = new XwSceincCollectinfo();
                                xwSceincCollectinfo.setBusinessEncryptid(business_encryptId);
                                xwSceincCollectinfo.setScenictypeEncryptid(sec_encryptId);
                                boolean sceColltemp = xwSceincCollectinfoReository.exists(Example.of(xwSceincCollectinfo));
                                if(sceColltemp){
                                    //查询到有相关记录
                                    xwSceincCollectinfoReository.deleteByScenicEncryptid(sec_encryptId);
                                }

                                //景区图集信息
                                XwScenicAtlasinfo xwScenicAtlasinfo = new XwScenicAtlasinfo();
                                xwScenicAtlasinfo.setBusinessEncryptid(business_encryptId);
                                xwScenicAtlasinfo.setScenicEncryptid(sec_encryptId);
                                boolean sceAtlastemp = xwScenicAtlasinfoRepository.exists(Example.of(xwScenicAtlasinfo));
                                if(sceAtlastemp){
                                    //查询到有相关记录
                                    xwScenicAtlasinfoRepository.deleteByScenicEncryptid(sec_encryptId);
                                }

                                //景区评论信息
                                XwSceincDiscussinfo xwSceincDiscussinfo = new XwSceincDiscussinfo();
                                xwSceincDiscussinfo.setBusinessEncryptid(business_encryptId);
                                xwSceincDiscussinfo.setScenicEncryptid(sec_encryptId);
                                boolean scedistemp = xwSceincDiscussinfoReopsitory.exists(Example.of(xwSceincDiscussinfo));
                                if(scedistemp){
                                    //查询到有相关记录
                                    xwSceincDiscussinfoReopsitory.deleteByScenicEncryptid(sec_encryptId);
                                }

                                //景区娱乐项目
                                XwSceincEntertainment xwSceincEntertainment = new XwSceincEntertainment();
                                xwSceincEntertainment.setBusinessEncryptid(business_encryptId);
                                xwSceincEntertainment.setScenicEncryptid(sec_encryptId);
                                boolean sceentertemp = xwSceincEntertainmentRepository.exists(Example.of(xwSceincEntertainment));
                                if(sceentertemp){
                                    //查询到有相关记录
                                    xwSceincEntertainmentRepository.deleteByScenicEncryptid(sec_encryptId);
                                }

                                //景区基本信息
                                XwScenicBasicinfo xwScenicBasicinfo = new XwScenicBasicinfo();
                                xwScenicBasicinfo.setBusinessEncryptid(business_encryptId);
                                xwScenicBasicinfo.setScenicEncryptid(sec_encryptId);
                                boolean scebastemp = xwScenicBasicinfoRepository.exists(Example.of(xwScenicBasicinfo));
                                if(scebastemp){
                                    //查询到有相关记录
                                    xwScenicBasicinfoRepository.deleteByScenicEncryptid(sec_encryptId);
                                }

                                //删除匹配对应商户类型的记录
                                XwCustomShop xwCustomShop = new XwCustomShop();
                                xwCustomShop.setShopEncryptid(sec_encryptId);
                                boolean shoptemp = xwCustomShopRepository.exists(Example.of(xwCustomShop));
                                if(shoptemp){
                                    xwCustomShopRepository.deleteByShopEncryptid(sec_encryptId);
                                }

                                //用户基本信息
                                XwUserinfo userinfo = xwUserinfoRepository.findByUserEncryptid(business_encryptId);
                                if(userinfo != null){
                                    userinfo.setUserRole("0");
                                    xwUserinfoRepository.save(userinfo);
                                }
                                xwBusinessInfoRepository.deleteByBusinessEncryptid(business_encryptId);
                            }

                            result.put("status", 0);
                            result.put("msg", "ok");

                        } else {
                            //不存在
                            result.put("status", 500);
                            result.put("msg", "该商家不存在！");
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    result.put("status", 500);
                    result.put("msg", e);
                }

            } else {
                result.put("status", 500);
                result.put("msg", "business_encryptId不能为空！");
            }
        }else {
            result.put("status",40001);
            result.put("msg","uid不能为空，请先登录后再操作！");
        }

        System.out.println("delbusinessinfo：" + result.toString());
        return result;
    }

    //获取商家主管审核信息
    @Override
    public JSONObject checkbusinessinfo(Integer pageindex, Integer pagesize, String starttime,
                                        String endtime, String sortfild, String sortway,String appliacnt,
                                        String business_type,String reviewStatus, String reviewer, String searchval,
                                        String searchkey, HttpServletRequest request) {


        JSONObject result = new JSONObject();
        String uid_encryptid = helper.ReadCookieMap(request,"uid_encryptid").toString();
        String uid = helper.ReadCookieMap(request,"uid").toString();
        if(!("").equals(uid) && !("").equals(uid_encryptid)){

            result = dal_xwBusinessinfo.getcheckbusinessinfo(pageindex,pagesize,starttime,endtime,sortfild,sortway,
                    appliacnt,business_type,reviewStatus,reviewer,searchval,searchkey,jdbcTemplate);

        }else {
            result.put("status", 40001);
            result.put("msg", "uid不可以为空，请登录后在操作！");
        }
        System.out.println("checkbusinessinfo:" + result.toString());
        return result;
    }



    @Override
    @Modifying
    @Transactional(rollbackFor = Exception.class)
    public JSONObject checkOperate(String business_encryptId, String type, String remark,HttpServletRequest request) {
        JSONObject result = new JSONObject();
        String uid_encryptid = helper.ReadCookieMap(request,"uid_encryptid").toString();
        String uid = helper.ReadCookieMap(request,"uid").toString();
        if(!("").equals(uid) && !("").equals(uid_encryptid)){
            if(!business_encryptId.equals("")){
                //当前操作人
                String reviewer_checkencryptId = helper.ReadCookieMap(request, "uid_encryptid").toString();
                try {
                    XwBusinessInfo xwBusinessInfo = new XwBusinessInfo();
                    xwBusinessInfo.setBusinessEncryptid(business_encryptId);
                    boolean temp =  xwBusinessInfoRepository.exists(Example.of(xwBusinessInfo));
                    if(temp){
                        XwBusinessInfo businessInfo = xwBusinessInfoRepository.findByBusinessEncryptid(business_encryptId);
                        if(businessInfo != null){
                            if(!type.equals("") && type != null){
                                try {
                                    //同意，拒绝操作
                                    businessInfo.setBusinessState(type);
                                    businessInfo.setReviewerCheckencryptid(reviewer_checkencryptId);
                                    businessInfo.setBusinessRemarks(remark);
                                    businessInfo.setBusinessUpdatetime(new Date());
                                    xwBusinessInfoRepository.save(businessInfo);
                                    if(type.equals("2")){
                                        //拒绝，拒绝后，更改用户类型为用户
                                        XwUserinfo xwUserinfo = xwUserinfoRepository.findByUserEncryptid(business_encryptId);
                                        if (xwUserinfo != null){
                                            xwUserinfo.setUserRole("0");
                                            xwUserinfo.setUserUpdatetime(new Date());
                                            xwUserinfoRepository.save(xwUserinfo);
                                        }
                                    }
                                    String statusName = "审核通过";
                                    if(type.equals("2")){
                                        statusName = "审核拒绝";
                                    }

                                    //发送电子邮件
                                    result = MailBusinfoCheck(business_encryptId,statusName,request);

                                    result.put("status", 0);
                                    result.put("msg", "ok");

                                }catch (Exception e){
                                    e.printStackTrace();
                                    result.put("status", 500);
                                    result.put("msg", e);
                                }
                            }
                        }else {
                            result.put("status", 40002);
                            result.put("msg", "该商家不存在！");
                        }
                    }else {
                        result.put("status", 40002);
                        result.put("msg", "该商家不存在！");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    result.put("status", 500);
                    result.put("msg", e);
                }

            }else {
                result.put("status", 500);
                result.put("msg", "business_encryptId不可以为空！");
            }
        }else {
            result.put("status", 40001);
            result.put("msg", "uid不可以为空，请登录后在操作！");
        }
        System.out.println("checkOperate:"+result.toString());
        return result;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public JSONObject checkRevoke(String business_encryptId, HttpServletRequest request) {
        JSONObject result = new JSONObject();

        String uid_encryptid = helper.ReadCookieMap(request,"uid_encryptid").toString();
        String uid = helper.ReadCookieMap(request,"uid").toString();
        if(!("").equals(uid) && !("").equals(uid_encryptid)){
            if(!business_encryptId.equals("")){
                //当前操作人
                String reviewer_checkencryptId = helper.ReadCookieMap(request, "uid_encryptid").toString();
                XwBusinessInfo xwBusinessInfo = xwBusinessInfoRepository.findByBusinessEncryptid(business_encryptId);
                if(xwBusinessInfo != null){

                    try {
                        xwBusinessInfo.setBusinessState("0");
                        xwBusinessInfo.setBusinessUpdatetime(new Date());
                        xwBusinessInfo.setReviewerCheckencryptid(reviewer_checkencryptId);
                        xwBusinessInfo.setBusinessRemarks("用户升级为商家，请核查商家信息");
                        xwBusinessInfoRepository.save(xwBusinessInfo);

                        result = MailBusinfoCheck(business_encryptId,"审核撤回",request);

                    }catch (Exception e){
                        e.printStackTrace();
                        result.put("status", 500);
                        result.put("msg", e);
                    }
                }else {
                    result.put("status", 500);
                    result.put("msg", "该商家不存在！");
                }
            }else {
                result.put("status", 500);
                result.put("msg", "business_encryptId不可以为空！");
            }
        }else {
            result.put("status", 40001);
            result.put("msg", "uid不可以为空，请登录后在操作！");
        }

        System.out.println("checkRevoke:"+result.toString());
        return result;
    }


    //发送商家信息审核电子邮件
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public JSONObject MailBusinfoCheck(String business_encryptId,String statusName,HttpServletRequest request) {

        JSONObject result = new JSONObject();
        String uid_encryptid = helper.ReadCookieMap(request,"uid_encryptid").toString();
        String uid = helper.ReadCookieMap(request,"uid").toString();
        if(!("").equals(uid) && !("").equals(uid_encryptid)){

            //获取发送邮件的基本信息
            JSONObject businfoObject = dal_xwBusinessinfo.getBusinessinfo(business_encryptId,jdbcTemplate);

            String userMail = businfoObject.getString("user_mail");
            if(!userMail.equals("")){
                Map<String,Object> hashMap = new HashMap<String,Object>();
                hashMap.put("Legal",businfoObject.getString("business_Legal"));
                hashMap.put("time",businfoObject.getString("createtime"));
                hashMap.put("name",businfoObject.getString("username"));
                hashMap.put("stauts",statusName);

                try {
                    Context context = new Context();
                    context.setVariables(hashMap);
                    String emailContext = templateEngine.process("MailBusinessTemple",context);
                    result = mailServcie.sendHtmlMail(userMail,"用户升级为商家审核通知",emailContext);

                }catch (Exception e){
                    e.printStackTrace();
                    result.put("status", 40002);
                    result.put("msg", e);
                }
            }
        }else {
            result.put("status", 40001);
            result.put("msg", "uid不可以为空，请登录后在操作！");
        }
        System.out.println("MailBusinfoCheck:"+result.toString());
        return result;
    }


    @Override
    public JSONObject delbussinessRefuse(HttpServletRequest request) {
        JSONObject result = new JSONObject();

        return result;
    }


    /**
     * 商家信息数据封装
     * @return
     */
    public XwBusinessInfo getRequestXwBusinessInfoData(String user_encryptId,String username,String business_tel,
                String business_Legal,String business_license,String CompanyName,String business_create,
                String business_Credit,String business_type,String Remarks,String applicant_checkencryptId,
                String farm_encryptId,String sec_encryptId){

        XwBusinessInfo businessInfo = new XwBusinessInfo();
        businessInfo.setBusinessEncryptid(user_encryptId);//商家加密id，就是原用户id
        businessInfo.setBusinessName(username);//用户的用户名，例如登录名
        businessInfo.setFarmEncryptid(farm_encryptId);//店铺加密id
        businessInfo.setSecEncryptid(sec_encryptId);//不是该商家，则默认为0
        businessInfo.setBusinessTel(business_tel);//联系电话
        businessInfo.setBusinessLegal(business_Legal);//法定代表人
        businessInfo.setBusinessLicense(business_license);//营业执照
        businessInfo.setBusinessCompanyname(CompanyName);//企业名称
        businessInfo.setBusinessCreate(business_create);//成立日期
        businessInfo.setBusinessCredit(business_Credit);//统一社会代码
        businessInfo.setBusinessType(business_type);//商户类型，1：农家，2：景区
        businessInfo.setBusinessState("0");//审核状态，0：审核中，1：审核通过，2：审核拒绝
        businessInfo.setBusinessRemarks(Remarks);//备注信息
        businessInfo.setBusinessUpdatetime(new Date()); //商家信息更新时间
        businessInfo.setBusinessCreatetime(new Date());//申请时间
        businessInfo.setApplicantCheckencryptid(applicant_checkencryptId);//申请为商家的申请操作者，还未审核，则没有审核人

        return businessInfo;
    }



    /**
     * 农家乐信息数据封装
     * @return
     */
    public XwFarmBasicinfo getRequestXwFarmBasicinfoData(String user_encryptId,String business_type,
                    String farm_tour_type,String Type_encryptId,String Business_area,String dining_reception,
                    String room,String scale,String consume,String city,String district,String address,
                    Integer tradestatus,String intr_info,String bus_route,String Self_route,
                    String farm_encryptId){

        XwFarmBasicinfo farmBasicinfo = new XwFarmBasicinfo();
        farmBasicinfo.setBusinessEncryptid(user_encryptId);//商家加密id，就是原用户id
        farmBasicinfo.setFarmEncryptid(farm_encryptId);//农家乐店铺加密id
        farmBasicinfo.setBusinessType(business_type);//商户类型，1：农家，2：景区
        farmBasicinfo.setFarmType(farm_tour_type);//农家类型
        farmBasicinfo.setFarmtypeEncryptid(Type_encryptId);//农家类型加密id（）
        farmBasicinfo.setFarmBusinessArea(Business_area);//经营面积
        farmBasicinfo.setFarmDiningReception(dining_reception);//用餐接待
        farmBasicinfo.setFarmRoom(room);//住宿容纳
        farmBasicinfo.setFarmScale(scale);//商铺规模
        farmBasicinfo.setFarmConsume(Double.parseDouble(consume));//人均消费
        farmBasicinfo.setFarmCity(city);//城市
        farmBasicinfo.setFarmDistrict(district);//地区区县
        farmBasicinfo.setFarmAddress(address);//住所
        farmBasicinfo.setFarmStatus(tradestatus);//营业状态:1:营业中，2：装修中，0：停业中
        farmBasicinfo.setFarmIntrInfo(intr_info);//农家乐店铺介绍
        farmBasicinfo.setFarmBusRoute(bus_route);//公交路线
        farmBasicinfo.setFarmSelfRoute(Self_route);//自驾路线
        farmBasicinfo.setFarmScore(0.0);//评分，默认为0分
        farmBasicinfo.setFarmViews(0);//访问量，默认为0
        farmBasicinfo.setFarmUpdatetime(new Date());//更新时间
        farmBasicinfo.setFarmCreatetime(new Date());//创建时间

        return farmBasicinfo;
    }



    /**
     * 景区信息数据封装
     * @return
     */
    public XwScenicBasicinfo getRequestXwScenicBasicinfoData(String user_encryptId,String business_type,
               String farm_tour_type,String Type_encryptId,Double scenic_Ticket,String tour_kftime,
               String scenic_suit,String sceni_suit_encryptId,String scenic_season,String scenic_grade,
               String city,String district, String address,String intr_info,String bus_route,String Self_route,
               String sce_encryptId){

        //景区店铺基本信息
        XwScenicBasicinfo scenicBasicinfo = new XwScenicBasicinfo();
        scenicBasicinfo.setBusinessEncryptid(user_encryptId);//商家加密id，就是原用户id
        scenicBasicinfo.setScenicEncryptid(sce_encryptId);//景区店铺加密id
        scenicBasicinfo.setBusinessType(business_type);//商户类型，1：农家，2：景区
        scenicBasicinfo.setScenictypeDesc(farm_tour_type);//景区类型
        scenicBasicinfo.setScenictypeEncryptid(Type_encryptId);//景区类型加密id
        scenicBasicinfo.setScenicTicket(scenic_Ticket);//门票
        scenicBasicinfo.setScenicDevelopTime(tour_kftime);//开放日期
        scenicBasicinfo.setScenicCrowdname(scenic_suit);//适合类型（适合人群）
        scenicBasicinfo.setSceniCrowdEncryptid(sceni_suit_encryptId);//适合人群加密id
        scenicBasicinfo.setScenicSeason(scenic_season);//适合的季节
        scenicBasicinfo.setScenicGrade(scenic_grade);//景区等级
        scenicBasicinfo.setScenicCity(city);//城市
        scenicBasicinfo.setScenicDistrict(district);//区县
        scenicBasicinfo.setScenicAddress(address);//住所
        scenicBasicinfo.setScenicIntrInfo(intr_info);//景区店铺介绍
        scenicBasicinfo.setScenicBusRoute(bus_route);//公交路线
        scenicBasicinfo.setScenicSelfRoute(Self_route);//自驾游路线
        scenicBasicinfo.setScenicScore(0.0); //评分,默认为0
        scenicBasicinfo.setScenicViews(0);//浏览量
        scenicBasicinfo.setScenicUpdatetime(new Date());//更新日期
        scenicBasicinfo.setScenicCreatetime(new Date());//创建日期

        return scenicBasicinfo;
    }




}
